import qs from "qs";
import router from "@/router";
import { getTokenValue, formatToken } from "@/utils/auth";
import axios from "axios";
import { encryptedData } from "@/utils/encrypt";
let loadingInstance: any;

/**
 * axios请求拦截器配置
 * @param config
 * @returns {any}
 */
const requestConf: any = async (config: any) => {
  const token = getTokenValue();
  // 不规范写法 可根据setting.config.js tokenName配置随意自定义headers
  // if (token) config.headers[tokenName] = token

  // 规范写法 不可随意自定义
  if (token) config.headers["Authorization"] = formatToken(token);
  if (
    (config.method === "post" ||
      config.method === "put" ||
      config.method === "delete") &&
    config.data
  ) {
    console.log("axios config", config.url, config.data);
    const data = await encryptedData(config.data);
    config.data = data;
  }
  if (
    config.data &&
    config.headers["Content-Type"] ===
      "application/x-www-form-urlencoded;charset=UTF-8"
  )
    config.data = qs.stringify(config.data);
  return config;
};

/**
 * axios响应拦截器
 * @param config 请求配置
 * @param data response数据
 * @param status HTTP status
 * @param statusText HTTP status text
 * @returns {Promise<*|*>}
 */
const handleData = async ({ data, status }: any) => {
  if (loadingInstance) loadingInstance.close();
  // 若data.code存在，覆盖默认code
  const code = data && data["code"] ? data["code"] : status;
  // 若code属于操作正常code，则status修改为200
  console.log("response", code, data);
  switch (code) {
    case 200:
      return data;
    case 201:
      return data;
    case 401:
      router.push({ path: "/login", replace: true }).then(() => {});
      break;
    case 402:
      break;
    case 403:
      router.push({ path: "/403" }).then(() => {});
      break;
    case 404:
      // Not Found
      //router.push({ path: '/404' }).then(() => {})
      return data;
  }
  // 异常处理
  return Promise.reject(data);
};

/**
 * @description axios初始化
 */
const { VITE_API_URL } = import.meta.env;
let apiBaseUrl = VITE_API_URL;
const instance = axios.create({
  baseURL: `${apiBaseUrl}`,
  timeout: 30000,
  headers: {
    "Content-Type": ""
  }
});

/**
 * @description axios请求拦截器
 */
instance.interceptors.request.use(requestConf, error => {
  return Promise.reject(error);
});

/**
 * @description axios响应拦截器
 */
instance.interceptors.response.use(
  response => handleData(response),
  error => {
    const { response } = error;
    if (response === undefined) {
      if (loadingInstance) loadingInstance.close();
      return {};
    } else return handleData(response);
  }
);

export default instance;
